try:
    import abc_decoder
except:
    import decoders.abc_decoder as abc_decoder

import wave
import pandas as pd
import numpy as np

def get_class():
    'None 表示这是抽象基类'
    return wav_decoder

class wav_decoder(abc_decoder.abs_decoder):
    def __init__(self):
        self.strFormat = 'wav'
    def get_name(self):
        return 'wav array'            
    def decode(self, file_path:str, **kwargs):        
        #todo: decode mp3 and return numpy array
        # each channel should be one dimension
        try:
            column_keys = kwargs['column_keys']
        except:
            column_keys = ['ax', 'ay']
        print('decoding %s file: %s' % (self.strFormat, file_path))

        """读取格式信息
        (声道数、量化位数、采样频率、采样点数、压缩类型、压缩类型的描述)
        """
        file = wave.open(file_path, "rb")
        # (nchannels, sampwidth, framerate, nframes, comptype, compname)
        params = file.getparams()
        nchannels, sampwidth, framerate, nframes = params[:4]
        # print(nchannels, sampwidth, framerate, nframes)
        # nchannels通道数 = 2
        # sampwidth量化位数 = 2
        # framerate采样频率 = 48000
        # nframes采样点数 = 499712

        # 读取nframes个数据，返回字符串格式
        str_data = file.readframes(nframes)
        # print("11111", len(str_data))
        file.close()

        """ 将字符串转换为数组, 得到一维的short类型的数组"""
        file = wave.open(file_path, "rb")
        params = file.getparams()
        # nchannels, nframes = params[:2]
        nchannels = params[0]
        nframes = params[3]
        strData = str_data
        # print(strData)
        wave_data = np.frombuffer(strData, dtype=np.short)
        # print(wave_data)

        # 赋值的归一化
        wave_data = wave_data * 100.0 / (max(abs(wave_data)))
        # print("len(wave_data)", len(wave_data))

        # 整合左声道和右声道的数据
        wave_data = np.reshape(wave_data, [nframes, nchannels])
        # print("xx",wave_data)
        file.close()
        # wave_data.shape = (-1, 2)   # -1的意思就是没有指定,根据另一个维度的数量进行分割

        """最后通过采样点数和取样频率计算出每个取样的时间"""
        file = wave.open(file_path, "rb")
        params = file.getparams()
        # framerate, nframes = params[3:4]
        framerate = params[2]
        nframes = params[3]
        time = np.arange(0, nframes) * (1.0 / framerate)
        file.close()
        # print("len(time)", len(time))   
        time = np.round(time, 5)

        """生成csv文件"""
        wave_data = wave_data
        dict_data = {'wave_data1': wave_data[:, 0], 'wave_data2': wave_data[:, 1]}
        dataframe = pd.DataFrame(dict_data, index=list(time))
        # dataframe = pd.DataFrame.from_dict({'Time(s)': frameTime(f), 'wave_data1': wave_data[:, 0], 'wave_data2': wave_data[:, 1]},
        #                                    orient='index')
        # invert = dataframe.T
        # dataframe.to_csv("wav_to_np.csv", index=True, sep=',')

        # mp3_data1 = data[:, 0]
        # mp3_data2 = data[:, 1]
        # ret = [mp3_data1, mp3_data2]
        if (column_keys[0] != 'rightChl') & (column_keys[1] != 'leftChn'):
            retWav = wave_data
        elif (column_keys[0] == 'leftChl') & (column_keys[1] != 'leftChn'):
            retWav = wave_data[:, 0]
        elif (column_keys[0] != 'leftChl') & (column_keys[1] == 'leftChn'):
            retWav = wave_data[:, 1]
        else:
            retWav = wave_data

        return retWav